<template>
  <div class="editUserDefault">
    <el-form ref="dataForm" :model="temp" :rules="rules" label-width="80px" class="fromData">
      <h2>基本信息</h2>
      <el-form-item v-if="eee" label="ID:">
        <span>{{ temp.user_id }}</span>
      </el-form-item>
      <el-form-item label="用户照片:">
        <div>
          <img :src="temp.user_facephoto" alt style="width:80px;height:80px">
        </div>
        <el-upload
          class="avatar-uploader"
          :drag="true"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名:">
        <el-input v-model="temp.user_name" style="width:200px;" />
      </el-form-item>
      <el-form-item label="性别:">
        <el-select v-model="temp.user_sex" class="filter-item" placeholder="选择性别">
          <el-option v-for="item in UserSexs" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号:">
        <el-input
          ref="phoneCards"
          v-model="temp.user_phonenumber"
          style="width:300px"
          @blur="phoneCard"
        />
      </el-form-item>
      <el-form-item label="身份证:">
        <el-input ref="userCards" v-model="temp.user_card" style="width:500px" @blur="userCard" />
      </el-form-item>
      <el-form-item label="入住时间:">
        <el-date-picker v-model="temp.user_livetime" type="datetime" placeholder="请选择时间" />
      </el-form-item>
      <el-form-item label="入住地址:">
        <el-input v-model="temp.user_address" style="width:700px" />
      </el-form-item>
      <el-form-item>
        <el-button v-if="aaa" type="primary" @click="creat">立即创建</el-button>
        <el-button v-if="bbb" type="primary" @click="update">立即更新</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
    <el-button
      style="float:right;  position: absolute;
  top:80px;
  right:50px;"
      @click="goBack"
    >返回用户列表</el-button>
    <el-button
      v-if="zzz"
      type="primary"
      style="float:right;  position: absolute;
  top:130px;
  right:50px;"
      @click="cls"
    >新建一个</el-button>
    <!-- 确认执行 -->
    <el-dialog :visible.sync="submit">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <span>确定执行此操作吗？</span>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submit = false">取消</el-button>
        <el-button v-if="ccc" type="primary" @click="creatData">确定新增</el-button>
        <el-button v-if="ddd" type="primary" @click="updateData">确定更新</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from '@/utils/request'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      imageUrl: '',
      phoneCards: '',
      userCards: '',
      UserSexs: ['男', '女'],
      rules: {},
      submit: false,
      aaa: false,
      bbb: true,
      ccc: true,
      ddd: false,
      eee: false,
      zzz: false,
      temp: {
        user_name: '',
        user_sex: '',
        user_card: '',
        user_facephoto: '',
        user_id: '',
        user_livetime: '',
        user_phonenumber: '',
        user_address: ''
      }
    }
  },
  mounted() {
    var data = this.$route.params.data
    if (data !== undefined) {
      if (data.user_id === '') {
        this.bbb = false
        this.aaa = true
        this.eee = false
        this.zzz = false
      } else {
        this.temp = data
        this.bbb = true
        this.aaa = false
        this.eee = true
        this.zzz = true
      }
    } else {
      this.bbb = false
      this.aaa = true
      this.eee = false
      this.zzz = false
    }
  },
  methods: {
    cls() {
      this.$router.go(0) // 刷新页面
    },
    // 增加
    creat() {
      this.submit = true
      this.ccc = true
      this.ddd = false
    },
    // 更新
    update() {
      this.submit = true
      this.ccc = false
      this.ddd = true
    },
    // 确认新增
    creatData() {
      this.$refs['dataForm'].validate(valid => {
        this.userCard()
        this.phoneCard()
        if (valid) {
          return request({
            url: '/v3/user/insert',
            method: 'post',
            headers: {
              account_type: '2'
            },
            data: this.temp
          }).then(res => {
            if (res.tip === '添加成功.') {
              this.dialogFormVisible = false
              this.$router.push({ path: '/archives/resident' })
              return res
            }
          })
        } else {
          Message({
            message: '添加失败，检查信息',
            type: 'error',
            duration: 2 * 1000
          })
        }
      })
    },
    // 确认修改
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        this.userCard()
        this.phoneCard()
        if (valid) {
          return request({
            url: '/v3/user/update',
            method: 'post',
            headers: {
              account_type: '2'
            },
            data: this.temp
          }).then(res => {
            if (res.tip === '修改成功.') {
              this.dialogFormVisible = false
              this.$router.push({ path: '/archives/resident' })
              return res
            }
          })
        } else {
          Message({
            message: '提交失败，检查信息',
            type: 'error',
            duration: 2 * 1000
          })
        }
      })
    },
    goBack() {
      this.$router.push({ path: '/archives/resident' })
    },
    // 身份证正则
    userCard() {
      var pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      var str = this.$refs['userCards'].value
      if (pattern.test(str) !== true) {
        Message({
          message: '身份证号错误',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    // 手机号正则
    phoneCard() {
      var pattern = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/
      var str = this.$refs['phoneCards'].value
      if (pattern.test(str) !== true) {
        Message({
          message: '手机号格式不正确',
          type: 'error',
          duration: 2 * 1000
        })
      }
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = ''
      this.imageUrl = URL.createObjectURL(file.raw)
      this.temp.user_facephoto = this.imageUrl
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style lang="scss" scoped>
.editUserDefault {
  position: relative;
  overflow: hidden;
  padding: 20px;
  .fromData {
    margin-top: 50px;
    padding: 20px;
    //上传头像
    .avatar-uploader {
      margin-top: 5px;
      margin-bottom: 5px;
    }
    .el-upload {
      border: 1px dashed #409eff;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }

    .el-upload__text {
      margin-top: 50px;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>
